using System;
using System.IO;

namespace MyWebApi.Api.Utils
{

    public static class FileSaveHelper
    {

        public static string Filesave(dynamic files , dynamic webRootPath)
        {
            
            // string contentRootPath = _hostingEnvironment.ContentRootPath;// 获取目录下的...Api路径 
            string showfilePath = "";   // 设置显示文件路径

            // Console.WriteLine(webRootPath);

            // 循环前端传过来的文件
            foreach (var formFile in files)
            {
                // 文件长度大于0
                if (formFile.Length > 0)
                {
                    int count = formFile.FileName.Split('.').Length;
                    string fileExt = formFile.FileName.Split('.')[count - 1];//文件扩展名
                    long fileSize = formFile.Length;//获得文件大小，以字节为单位
                    string newFileName = System.Guid.NewGuid().ToString() + "." + fileExt;//随机生成新文件
                    // 路径拼接
                    var filePath = webRootPath + "/upload";
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }

                    filePath = webRootPath + "/upload/" + newFileName;
                    showfilePath = "upload/" + newFileName;
                    // 用文件帮助类创建文件路径
                    FileHelper.CreateFile(filePath);

                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        formFile.CopyTo(stream);
                    }


                    Console.WriteLine(showfilePath);
                }
            }

            return showfilePath;
        }

    }

}